import classNames from 'classnames';
import React from 'react';
import MyHidden from './MyHidden'
import { useSelector, useDispatch } from 'react-redux';
import * as store from './reducers/partsSlice';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';
import Tooltip from '@mui/material/Tooltip';
import FolderOpenIcon from '@mui/icons-material/FolderOpen';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
const electron = window.require('electron')
const ipc = electron.ipcRenderer
function getFileSizeString(bytes) {
  const prefixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];

  let size = bytes;
  let prefixIndex = 0;

  while (size > 900) {
    // prefer "0.9 KB" to "949 bytes"
    size /= 1024;
    prefixIndex++;
  }

  return Math.round(size * 10) / 10 + ' ' + prefixes[prefixIndex];
}
export default function DownloadManager(props) {
  const dispatch = useDispatch();
  var show_download = useSelector((state) => state.show_download);
  const [state, setState] = React.useState({
    lastDownloadCompleted: null,
    downloadItems: {},
  });
  React.useEffect(() => {
    initialize();
  }, [])
  const removeItem = (path) => {
    let items = state.downloadItems;
    // let new_items=state.downloadItems.filter((item,key) =>key!==path);
    delete items[path];
    setState((state) => ({ ...state, downloadItems: items }));
    if (Object.keys(items).length === 0) {
      hide();
      // setState(state => ({ ...state, isShown: false }));
      // webviews.adjustMargin([0, 0, height * -1, 0]);
    }
  };
  const openFolder = (path) => {
    electron.shell.showItemInFolder(path);
  };
  const onItemClicked = (path) => {
    if (state.downloadItems[path] && state.downloadItems[path].status === 'completed') {
      electron.shell.openPath(path);
      // provide a bit of time for the file to open before the download bar disappears
      setTimeout(() => {
        removeItem(path);
      }, 100);
    }
  };
  const onItemDragged = (path) => {
    //todo
    // remote.app.getFileIcon(path, {}).then(function (icon) {
    //   remote.getCurrentWebContents().startDrag({
    //     file: path,
    //     icon: icon
    //   })
    // })
  };
  const onDownloadCompleted = () => {
    lastDownloadCompleted = Date.now();
    setTimeout(() => {
      if (
        Date.now() - lastDownloadCompleted >= 120000 &&
        Object.values(state.downloadItems).filter(
          (i) => i.status === 'progressing'
        ).length === 0
      ) {
        hide();
      }
    }, 120 * 1000);
  };
  const createItem = (downloadItem) => {
    let completed;
    let loading;
    let progress_hidden;
    let dropdown_hidden;
    let openFolder_hidden;
    let infoBox_textContent;
    let detailedInfoBox_textContent;
    let progress_style = {};
    if (downloadItem.status === 'completed') {
      completed = true;
      loading = false;
      progress_hidden = true;
      dropdown_hidden = true;
      openFolder_hidden = false;
      infoBox_textContent = l('downloadStateCompleted');
      detailedInfoBox_textContent = l('downloadStateCompleted');
    } else if (downloadItem.status === 'interrupted') {
      completed = false;
      loading = false;
      progress_hidden = true;
      dropdown_hidden = true;
      openFolder_hidden = true;
      infoBox_textContent = l('downloadStateFailed');
      detailedInfoBox_textContent = l('downloadStateFailed');
    } else {
      completed = true;
      loading = false;
      progress_hidden = false;
      dropdown_hidden = false;
      openFolder_hidden = true;
      infoBox_textContent = getFileSizeString(downloadItem.size.total);
      detailedInfoBox_textContent =
        getFileSizeString(downloadItem.size.received) +
        ' / ' +
        getFileSizeString(downloadItem.size.total);
      // the progress bar has a minimum width so that it's visible even if there's 0 download progress
      const adjustedProgress =
        0.025 + (downloadItem.size.received / downloadItem.size.total) * 0.975;
      progress_style = { transform: 'scaleX(' + adjustedProgress + ')' };
    }
    let cn = classNames({
      'download-item': true,
      loading: loading,
      completed: completed,
    });
    progress_style["display"] = progress_hidden ? "none" : "inline";
    return (
      <ListItem
        key={downloadItem.path}
        role="listitem"
        draggable="true"
        onDragStart={(e) => {
          e.preventDefault();
          onItemDragged(downloadItem.path);
        }}
        onClick={() => {
          onItemClicked(downloadItem.path);
        }}
      >
        <ListItemText>{downloadItem.name}</ListItemText>
        <ListItemText>{infoBox_textContent}</ListItemText>
        <ListItemText>
          {detailedInfoBox_textContent}
        </ListItemText>
        <div
          className="download-progress"
          style={progress_style}
        ></div>
        <Tooltip title="cancel">
          <IconButton
            style={{ display: dropdown_hidden ? "none" : "inline" }}
            onClick={(e) => {
              ipc.send('cancelDownload', downloadItem.path);
              removeItem(downloadItem.path);
            }}
            className="download-action-button i carbon:incomplete-cancel"
          ><CloseIcon /> </IconButton>
        </Tooltip>
        <IconButton
          style={{ display: openFolder_hidden ? "none" : "inline" }}
          onClick={(e) => {
            e.stopPropagation();
            openFolder(downloadItem.path);
            removeItem(downloadItem.path);
          }}
          className="download-action-button i carbon:folder"
        ><FolderOpenIcon /></IconButton>
      </ListItem>
    );
    // DownloadManager.downloadBarElements[downloadItem.path] = { container, title, infoBox, detailedInfoBox, progress, dropdown, openFolder }
  };
  const initialize = () => {
    ipc.on('download-info', (e, info) => {
      if (!info.path) {
        // download save location hasn't been chosen yet
        return;
      }

      if (info.status === 'cancelled') {
        removeItem(info.path);
        return;
      }

      if (info.status === 'completed') {
        onDownloadCompleted();
      }

      if (!state.downloadItems[info.path]) {
        let items = state.downloadItems;
        items[info.path] = info;
        setState((state) => ({ ...state, downloadItems: items }));
        show();
        // createItem(info)
      }
      //update Item;
      let items = state.downloadItems;
      items[info.path] = info;
      setState((state) => ({ ...state, downloadItems: items }));
    });
  };
  // DownloadManager.initialize = initialize;
  let items_ele = [];
  let key;
  for (key in state.downloadItems) {
    items_ele.push(createItem(state.downloadItems[key]));
  }
  return (
    <MyHidden title="download" on_hidden={() => {
      dispatch(store.partsSlice.actions.SHOW_DOWNLOAD(false))
    }} hidden={!show_download}>
      <List>
        {items_ele.length == 0 ? "no download" : items_ele}
      </List>
    </MyHidden>
  );
}
